

<template>
  <view class="Mall4j container">
    <view class="coupons">
      <view class="banner">
        <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/coupon-banner.png" mode="widthFix" />
      </view>
      <view class="con-box">
        <view v-if="prodCouponList.length" class="c-tit">{{ i18n.universalCoupon }}</view>
        <view v-if="prodCouponList.length" class="special">
          <view v-for="(item, index) in prodCouponList" :key="index" class="item">
            <view :class="'item-box ' + ((item.canGoUse) ? 'received' : ((!item.stocks && !item.curUserReceiveCount) ? 'robbed' : ''))">
              <!-- 多商品券 -->
              <view v-if="item.prods.length > 1" class="item-con">
                <view class="shop-msg">{{ item.couponName }}</view>
                <view class="prod-msg">
                  <view v-for="(prod, prodIndex) in item.prods" :key="prodIndex" class="p-item">
                    <view class="img">
                      <image v-if="prod.pic" :src="prod.pic" />
                      <image v-else src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/def.png" mode="aspectFit" />
                    </view>
                    <view class="price">￥{{ prod.price }}</view>
                  </view>
                </view>
              </view>
              <view v-if="item.prods.length > 1" class="item-btn">
                <view class="btn-box">
                  <view v-if="item.couponType == 1" class="number">
                    <view class="symbol">￥</view>
                    <view class="text">{{ item.reduceAmount }}</view>
                  </view>
                  <view v-if="item.couponType == 2" class="number">
                    <view class="text">{{ item.couponDiscount }}</view>
                    <view class="symbol">{{ i18n.discount }}</view>
                  </view>
                  <view class="condition">{{ i18n.available }}{{ item.cashCondition }}{{ i18n.availableUse }}</view>
                  <view class="progress-box">
                    <view v-if="item.stocks == 0" class="text">{{ i18n.nocoupons }}</view>
                    <view v-if="item.stocks != 0" class="text">{{ i18n.haveCoupons }}{{ wxs.rounding((item.sourceStock - item.stocks) * 100 / item.sourceStock) }}%</view>
                    <view class="progress" :style="'width: ' + (wxs.rounding((item.sourceStock - item.stocks) * 100 / item.sourceStock)) + '%'" />
                  </view>
                  <view v-if="!item.canGoUse && item.stocks" class="btn" :data-couponid="item.couponId" data-coupontype="2" :data-couponindex="index" @tap="receiveCoupon">{{ i18n.getIt }}</view>
                  <view v-if="item.canGoUse" class="btn" :data-couponid="item.couponId" :data-prodlist="item.prods" @tap="useCoupon">{{ i18n.toUse }}</view>
                  <view v-if="!item.canGoUse && !item.stocks" class="btn gray-btn">{{ i18n.nocoupons }}</view>
                </view>
              </view>
              <!-- /多商品券 -->
              <!-- 单商品券 -->
              <view v-if="item.prods.length == 1" class="left">
                <view class="img">
                  <image :src="item.prods[0].pic" />
                </view>
                <view class="text-box">
                  <view class="goods-name">{{ item.prods[0].prodName }}</view>
                  <view class="coupon-number">
                    <view v-if="item.couponType == 1" class="number">
                      <view class="symbol">￥</view>
                      <view class="text">{{ item.reduceAmount }}</view>
                    </view>
                    <view v-if="item.couponType == 2" class="number">
                      <view class="text">{{ item.couponDiscount }}</view>
                      <view class="symbol">{{ i18n.discount }}</view>
                    </view>
                    <view class="condition">{{ i18n.available }}{{ item.cashCondition }}{{ i18n.availableUse }}</view>
                  </view>
                </view>
              </view>
              <view v-if="item.prods.length == 1" class="right">
                <view class="btn-box">
                  <view v-if="item.stocks == 0" class="progress-text">{{ i18n.nocoupons }}</view>
                  <view v-if="item.stocks != 0" class="progress-text">{{ i18n.haveCoupons }}{{ wxs.rounding((item.sourceStock - item.stocks) * 100 / item.sourceStock) }}%</view>
                  <view class="progress-box">
                    <view class="progress" :style="'width: ' + (wxs.rounding((item.sourceStock - item.stocks) * 100 / item.sourceStock)) + '%'" />
                  </view>
                  <view v-if="!item.canGoUse && item.stocks" class="btn" :data-couponid="item.couponId" data-coupontype="2" :data-couponindex="index" @tap="receiveCoupon">{{ i18n.getIt }}</view>
                  <view v-if="item.canGoUse" class="btn" :data-couponid="item.couponId" :data-prodlist="item.prods" @tap="useCoupon">{{ i18n.toUse }}</view>
                  <view v-if="!item.canGoUse && !item.stocks" class="btn gray-btn">{{ i18n.nocoupons }}</view>
                </view>
              </view>
              <!-- /单商品券 -->
              <!-- 已领取 -->
              <view v-if="item.canGoUse || item.userHasCount !== 0" class="icon">
                <image :src="isEn? 'https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/coupon-received-en.png':'https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/coupon-received.png'" />
              </view>
              <!-- 已抢光 -->
              <view v-if="!item.canGoUse && !item.stocks" class="icon">
                <image :src="isEn? 'https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/coupon-robbed-en.png': 'https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/coupon-robbed.png'" />
              </view>
            </view>
          </view>
        </view>
      </view>

      <view v-if="prodCouponList.length > 6 && loadAll" class="loadall">{{ i18n.endTips }}</view>

      <!-- 空 -->
      <empty v-if="prodCouponList.length==0" />
    </view>
  </view>
</template>

<script module="wxs" lang="wxs" src="../../../wxs/number.wxs"></script>

<script>
// pages/coupon-center/coupon-center.js
var http = require("../../../utils/http.js");
var config = require("../../../utils/config.js");
var util = require("../../../utils/util.js");
import empty from "@/components/empty-tips/index.vue";

export default {
  data () {
    return {
      prodCouponList: [],
      // 商品券列表
      selectedCouponId: 0,
      // 要领取的优惠券id
      current: 1,
      size: 6,
      // 当前页数
      pages: 1, // 总页数
      loadAll: false, // 已加载全部
      isEn: uni.getStorageSync('lang') == 'en' ? true : false, // 是否为英文
    };
  },

  components: {
    empty
  },

  computed: {
    i18n () {
      return this.$t('index')
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { //获取通用列表
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //头部导航标题
    uni.setNavigationBarTitle({
      title: this.i18n.couponCenter
    });

    this.getProdCouponList(1);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.current < this.pages) {
      this.getProdCouponList(this.current + 1);
    } else {
      this.setData({
        loadAll: true
      })
    }
  },
  methods: {
    /**
     * 获取指定商品券
     */
    getProdCouponList (cur) {
      var params = {
        url: "/p/myCoupon/getCouponPage",
        method: "GET",
        data: {
          current: cur,
          size: this.size
        },
        callBack: res => {
          res.records = res.records.filter(el => el.prods && el.prods.length > 0)
          let list = [];
          if (res.current == 1) {
            list = res.records ? res.records : []
          } else {
            list = this.prodCouponList;
            list = list.concat(res.records);
          }
          this.setData({
            prodCouponList: list,
            pages: res.pages,
            current: res.current
          });
          this.initCouponCanGoUseFlag(res.records);
        }
      };
      http.request(params);
    },

    /**
     * 初始化优惠券去可以使用的标记
     */
    initCouponCanGoUseFlag (couponList) {
      if (couponList) {
        couponList.forEach(coupon => {
          coupon.canGoUse = coupon.curUserReceiveCount >= coupon.limitNum;
        })
      }
    },

    /**
     * 设置优惠券去可以使用的标记
     */
    setCouponCanGoUseFlag (index, couponType) {
      if (couponType == 1) {
        var tempCouponList = this.couponList;
        tempCouponList[index].canGoUse = true;
        tempCouponList[index].stocks -= 1;
        this.setData({
          couponList: tempCouponList
        });
      } else if (couponType == 2) {
        var tempCouponList = this.prodCouponList;
        tempCouponList[index].canGoUse = true;
        tempCouponList[index].stocks -= 1;
        this.setData({
          prodCouponList: tempCouponList
        });
      }
    },

    /**
      * 立即领取
      */
    receiveCoupon (e) {
      this.setData({
        selectedCouponId: e.currentTarget.dataset.couponid
      });
      util.checkAuthInfo(() => {
        if (this.selectedCouponId) {
          const params = {
            url: '/p/myCoupon/receive',
            method: 'POST',
            data: this.selectedCouponId,
            callBack: res => {
              uni.showToast({
                title: this.i18n.successfullyReceived,
                icon: 'success',
                duration: 2000
              });
              this.setCouponCanGoUseFlag(e.currentTarget.dataset.couponindex, e.currentTarget.dataset.coupontype);
            }
          }
          http.request(params)
        }
      });
    },

    /**
     * 立即使用
     */
    useCoupon (e) {
      let url = '/pages/prod-classify/prod-classify?sts=4';
      let couponId = e.currentTarget.dataset.couponid;
      var title = this.i18n.couponEventGoods;
      var prodList = e.currentTarget.dataset.prodlist;

      if (prodList && prodList.length == 1) {
        // uni.navigateTo({
        //   url: '/pages/prod/prod?prodid=' + prodList[0].prodId
        // });
        this.$Router.push({
          path: '/pages/prod/prod',
          query: {
            prodid: prodList[0].prodId
          }
        })
      } else {
        if (couponId) {
          url += "&tagid=" + couponId + "&title=" + title;
        }

        uni.navigateTo({
          url: url
        });
      }
    }

  }
};
</script>
<style>
@import "./coupon-center.css";
</style>
